package xh;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import sun.misc.BASE64Decoder;
import xh.protocol.DownLoadRequestHeader;
import xh.protocol.DownLoadResponseHeader;

import java.io.*;
import java.lang.reflect.Array;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;

/**
 * Created by Administrator on 2016/7/6.
 */
public class FileServer {

    private Thread listenThread;

    FileListManager fileListManager;

    public FileServer(FileListManager fileListManager) {
        this.fileListManager = fileListManager;
    }

    public void start() {

        listenThread = new Thread(new Acceptor());
        listenThread.start();
    }


    private class Acceptor implements Runnable {

        public void run() {

            try {
                ServerSocket serverSocket = new ServerSocket(Global.FileServerPort);

                while (true) {

                    Socket accept = serverSocket.accept();

                    new Thread(new RequestResovler(accept)).start();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }


    private class RequestResovler implements Runnable {

        Socket socket;

        RequestResovler(Socket socket) {
            this.socket = socket;
        }

        public void run() {

            //TODO


            try {
                InputStream is = socket.getInputStream();
                DataInputStream di = new DataInputStream(is);

                int Hlength = di.readInt();

                byte[] bytes = new byte[Hlength];
                int read = di.read(bytes);

                DownLoadRequestHeader h = JSON.parseObject(new String(bytes, "utf-8"), DownLoadRequestHeader.class);


                //get file by id
                String fileName = fileListManager.getFileName(h.getFileId());
                if (fileName == null) {
                    DownLoadResponseHeader rh = new DownLoadResponseHeader();
                    rh.setResultCode(1);
                    rh.setResultString("no such file");

                    DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
                    dataOutputStream.writeInt(bytes.length);
                    dataOutputStream.write(bytes);
                    dataOutputStream.close();
                    return;
                }

                RandomAccessFile file = new RandomAccessFile(new File(Global.BasePath, fileName), "r");
                file.seek(h.getOffset());

                //response
                DownLoadResponseHeader rh = new DownLoadResponseHeader();
                rh.setResultCode(0);
                rh.setResultString("success");
                rh.setFileBufLength((int) (file.length()-h.getOffset()));
                rh.setFileName(fileName);

                String s = JSON.toJSONString(rh);

                bytes = s.getBytes("utf-8");
                DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
                dataOutputStream.writeInt(bytes.length);
                dataOutputStream.write(bytes);

                while (true) {
                    byte[] buf = new byte[1024*1024];
                    int l = file.read(buf);
                    if (l > 0) {
//                        System.out.println("readl="+l);
                        dataOutputStream.write(buf, 0, l);
                    } else {
                        System.out.println("read file ok");
                        break;
                    }
                }

//                dataOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
//        FileServer fileServer = new FileServer();
//        fileServer.start();
    }
}
